<?php

namespace app\admin\service;

use app\model\CrisisLevelModel;
use app\model\CrisisTypeModel;
use app\model\DepartmentLevelModel;
use app\model\DepartmentModel;
use app\model\FollowUserModel;
use app\model\InterfereUserModel;
use app\model\RoleModel;
use app\model\UserModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Service;

class InterfereImportService extends Service
{
    public string $message;
    public int $line;

    /**
     * 获取性别对应值
     * @param $sex
     * @return int
     */
    public function sexValue($sex): int
    {
        $data = [
            '男' => 1,
            '女' => 2
        ];
        return $data[$sex] ?? 0;
    }

    /**
     * 关注人群导入格式
     * @return array[]
     */
    public function getFollowUserConfig(): array
    {
        return [
            [
                'key' => 'A',
                'name' => '所在部门层级',
                'field' => 'department_name',
                'required' => true
            ],
            [
                'key' => 'B',
                'name' => '登录账号',
                'field' => 'username',
                'required' => true
            ],
            [
                'key' => 'C',
                'name' => '真实姓名',
                'field' => 'name',
                'required' => true
            ],
            [
                'key' => 'D',
                'name' => '性别',
                'field' => 'sex',
                'required' => true
            ],
            [
                'key' => 'E',
                'name' => '关注等级',
                'field' => 'level',
                'required' => false
            ],
            [
                'key' => 'F',
                'name' => '关注原因',
                'field' => 'reason',
                'required' => false
            ]
        ];
    }

    /**
     * 关注人群导入格式-学院版
     * @return array[]
     */
    public function getSchoolFollowUserConfig(): array
    {
        return [
            [
                'key' => 'A',
                'name' => '学部/年级/班级',
                'field' => 'department_name',
                'required' => true
            ],
            [
                'key' => 'B',
                'name' => '制阶段',
                'field' => 'stage',
                'required' => true
            ],
            [
                'key' => 'C',
                'name' => '登录账号',
                'field' => 'username',
                'required' => true
            ],
            [
                'key' => 'D',
                'name' => '真实姓名',
                'field' => 'name',
                'required' => true
            ],
            [
                'key' => 'E',
                'name' => '性别',
                'field' => 'sex',
                'required' => true
            ],
            [
                'key' => 'F',
                'name' => '关注等级',
                'field' => 'level',
                'required' => true
            ],
            [
                'key' => 'G',
                'name' => '关注原因',
                'field' => 'reason',
                'required' => true
            ]
        ];
    }

    /**
     * 干预人群导入格式
     * @return array[]
     */
    public function getInterfereUserConfig(): array
    {
        return [
            [
                'key' => 'A',
                'name' => '所在部门层级',
                'field' => 'department_name',
                'required' => true
            ],
            [
                'key' => 'B',
                'name' => '登录账号',
                'field' => 'username',
                'required' => true
            ],
            [
                'key' => 'C',
                'name' => '真实姓名',
                'field' => 'name',
                'required' => true
            ],
            [
                'key' => 'D',
                'name' => '性别',
                'field' => 'sex',
                'required' => true
            ],
            [
                'key' => 'E',
                'name' => '预检建议优先度',
                'field' => 'priority',
                'required' => true
            ],
            [
                'key' => 'F',
                'name' => '疑似问题类型',
                'field' => 'type_id',
                'required' => true
            ],
            [
                'key' => 'G',
                'name' => '危险风险等级',
                'field' => 'level_id',
                'required' => true
            ],
            [
                'key' => 'H',
                'name' => '干预原因',
                'field' => 'describe',
                'required' => true
            ]
        ];
    }

    /**
     * 干预人群导入格式-学院版
     * @return array[]
     */
    public function getSchoolInterfereUserConfig(): array
    {
        return [
            [
                'key' => 'A',
                'name' => '学部/年级/班级',
                'field' => 'department_name',
                'required' => true
            ],
            [
                'key' => 'B',
                'name' => '制阶段',
                'field' => 'stage',
                'required' => true
            ],
            [
                'key' => 'C',
                'name' => '登录账号',
                'field' => 'username',
                'required' => true
            ],
            [
                'key' => 'D',
                'name' => '真实姓名',
                'field' => 'name',
                'required' => true
            ],
            [
                'key' => 'E',
                'name' => '性别',
                'field' => 'sex',
                'required' => true
            ],
            [
                'key' => 'F',
                'name' => '预检建议优先度',
                'field' => 'priority',
                'required' => true
            ],
            [
                'key' => 'G',
                'name' => '疑似问题类型',
                'field' => 'type_id',
                'required' => true
            ],
            [
                'key' => 'H',
                'name' => '危险风险等级',
                'field' => 'level_id',
                'required' => true
            ],
            [
                'key' => 'I',
                'name' => '干预原因',
                'field' => 'describe',
                'required' => true
            ]
        ];
    }

    /**
     * 关注人群导入
     * @param string $path 导入文件地址
     * @param array $userData 导入人信息
     * @return bool
     */
    public function FollowUser(string $path, array $userData): bool
    {
        try {
            $ext = '.xlsx';
            $save_name = '/upload/'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            if (!file_put_contents('./public' . $save_name . $ext, file_get_contents($path))) throw new \Exception('文件加载失败！');
            $spreadSheet = IOFactory::load('./public' . $save_name . $ext);
            $sheetNames = $spreadSheet->getSheetNames();
            if ($sheetNames[0] != "关注人群") throw new \Exception('请上传正确的模板！');
            $sheet = $spreadSheet->getSheet(0);
            $limit = $sheet->getHighestDataRow('A');
            if ($limit < 4) throw new \Exception('请正确填写信息！');
            $Config = $this->getFollowUserConfig();
            $UserModel = new UserModel();
            $FollowUserModel = new FollowUserModel();
            $DepartmentModel = new DepartmentModel();
            $RoleModel = new RoleModel();
            $UserService = new UserService($this->app);
            $SaveData = [];
            $time = time();
            $error = [];
            for ($i = 4; $i <= $limit; $i++) {
                $data = [];
                foreach ($Config as $value) {
                    $variate = $sheet->getCell($value['key'] . $i)->getValue();
                    if (empty($variate) && $value['required']) {
                        $error[] = '第'.$i.'行'.$value['key'] . $i.'列'.$value['name'] . '不能为空！';
//                        throw new \Exception($value['name'] . '不能为空！');
                    }
                    $data[$value['field']] = $variate;
                }
                $SaveData[] = $data;
            }
            if (!empty($error)) {
                throw new \Exception(implode("\n", $error));
            }
            $roleInfo = $RoleModel->where([
                ['unit_id','=',$userData['unit_id']],
                ['mode','=',3]
            ])->find();
            if (!$roleInfo) throw new \Exception('普通用户角色未创建！');
            $AddData = [];
            foreach ($SaveData as $item){
                $item['sex'] = $this->sexValue($item['sex']);
                $department_name = explode('_', $item['department_name']);
                $pid = 0;
                foreach ($department_name as $k => $v) {
                    $department_id = $DepartmentModel->where([
                        ['unit_id', '=', $userData['unit_id']],
                        ['name', '=', $v],
                    ])->value('id');
                    if (!$department_id) {
                        $pid = $DepartmentModel->insertGetId([
                            'unit_id' => $userData['unit_id'],
                            'pid' => $pid,
                            'level' => $k + 1,
                            'name' => $v,
                            'type' => 1,
                            'time' => $time
                        ]);
                    }else{
                        $pid = $department_id;
                    }
                }
                $user = $UserModel->where('username', '=', $item['username'])->field('id,department_id')->find();
                if (!$user){
                    $uid = $UserModel->insertGetId([
                        'company_id' => $userData['company_id'],
                        'areas_id' => $userData['areas_id'],
                        'platform_id' => $userData['platform_id'],
                        'unit_id' => $userData['unit_id'],
                        'department_id' => $pid,
                        'role_id' => $roleInfo['id'],
                        'role_mode' => $roleInfo['mode'],
                        'type' => 4,
                        'username' => $item['username'],
                        'password' => encrypt_password(env('USER_PASSWORD')),
                        'sex' => $item['sex'],
                        'name' => $item['name'],
                        'avatar' => $item['sex'] == 1 ? $UserService->getDefaultAvatar('male') : $UserService->getDefaultAvatar('female'),
                        'province_id' => $userData['province_id'],
                        'city_id' => $userData['city_id'],
                        'area_id' => $userData['area_id'],
                        'province_name' => $userData['province_name'],
                        'city_name' => $userData['city_name'],
                        'area_name' => $userData['area_name'],
                        'time' => $time
                    ]);
                }else{
                    if ($user['department_id'] != $pid) throw new \Exception('账号【'.$item['username'].'】与部门【'.$item['department_name'].'】不匹配');
                    $uid = $user['id'];
                }
                $AddData[] = [
                    'unit_id' => $userData['unit_id'],
                    'operator_uid' => $userData['id'],
                    'uid' => $uid,
                    'level' => match ($item['level']) {
                        '轻度' => 1,
                        '中度' => 2,
                        '重度' => 3,
                        '密切' => 4,
                        default => 0
                    },
                    'reason' => $item['reason']??'',
                    'channel' => 8,
                    'time' => $time
                ];
            }
            if (!empty($AddData)) $FollowUserModel->insertAll($AddData);
            return true;
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            $this->line = $e->getLine();
            return false;
        }
    }

    /**
     * 关注人群导入-学院版
     * @param string $path 导入文件地址
     * @param array $userData 导入人信息
     * @return bool
     */
    public function SchoolFollowUser(string $path, array $userData): bool
    {
        try {
            $ext = '.xlsx';
            $save_name = '/upload/'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            if (!file_put_contents('./public' . $save_name . $ext, file_get_contents($path))) throw new \Exception('文件加载失败！');
            $spreadSheet = IOFactory::load('./public' . $save_name . $ext);
            $sheetNames = $spreadSheet->getSheetNames();
            if ($sheetNames[0] != "学院制关注人群") throw new \Exception('请上传正确的模板！');
            $sheet = $spreadSheet->getSheet(0);
            $limit = $sheet->getHighestDataRow('A');
            if ($limit < 4) throw new \Exception('请正确填写信息！');
            $Config = $this->getSchoolFollowUserConfig();
            $UserModel = new UserModel();
            $FollowUserModel = new FollowUserModel();
            $DepartmentModel = new DepartmentModel();
            $DepartmentLevelModel = new DepartmentLevelModel();
            $RoleModel = new RoleModel();
            $UserService = new UserService($this->app);
            $SaveData = [];
            $time = time();
            $error = [];
            for ($i = 4; $i <= $limit; $i++) {
                $data = [];
                foreach ($Config as $value) {
                    $variate = $sheet->getCell($value['key'] . $i)->getValue();
                    if (empty($variate) && $value['required']) {
                        $error[] = '第'.$i.'行'.$value['key'] . $i.'列'.$value['name'] . '不能为空！';
//                        throw new \Exception($value['name'] . '不能为空！');
                    }
                    $data[$value['field']] = $variate;
                }
                $SaveData[] = $data;
            }
            if (!empty($error)){
                throw new \Exception(implode("\n", $error));
            }
            $roleInfo = $RoleModel->where([
                ['unit_id','=',$userData['unit_id']],
                ['mode','=',3]
            ])->find();
            if (!$roleInfo) throw new \Exception('普通用户角色未创建！');
            $AddData = [];
            foreach ($SaveData as $item){
                $item['sex'] = $this->sexValue($item['sex']);
                $is_department = 1;
                $department_name = explode('_', $item['department_name']);
                $pid = 0;
                foreach ($department_name as $v) {
                    $department_id = $DepartmentModel->where([
                        ['unit_id', '=', $userData['unit_id']],
                        ['name', '=', $v],
                    ])->value('id');
                    if (!$department_id) {
                        $is_department = 0;
                    }
                    $pid = $department_id;
                }
                if ($is_department == 0) {
                    $pid = 0;
                    //创建部门
                    $stage = explode('_', $item['stage']);
                    if (count($stage) != 2) throw new \Exception($item['stage'] . '格式错误！');
                    $LevelInfo = $DepartmentLevelModel->where([
                        ['name', '=', $stage[0]],
                        ['unit_id', '=', $userData['unit_id']]
                    ])->find()->toArray();
                    if (!$LevelInfo) throw new \Exception($item['stage'] . '不存在！');
                    $stageData = json_decode($LevelInfo['level_rules'], true);
                    foreach ($department_name as $k => $v) {
                        $department_id = $DepartmentModel->where([
                            ['pid', '=', $pid],
                            ['name', '=', $v],
                            ['unit_id', '=', $userData['unit_id']]
                        ])->value('id');
                        if (!$department_id) {
                            $pid = match ($k) {
                                0 => $DepartmentModel->insertGetId([
                                    'unit_id' => $userData['unit_id'],
                                    'pid' => $pid,
                                    'level' => $k + 1,
                                    'name' => $v,
                                    'type' => 2,
                                    'mode' => $LevelInfo['id'],
                                    'time' => time()
                                ]),
                                default => $DepartmentModel->insertGetId([
                                    'unit_id' => $userData['unit_id'],
                                    'pid' => $pid,
                                    'level' => $k + 1,
                                    'name' => $v,
                                    'type' => 2,
                                    'mode' => $LevelInfo['id'],
                                    'stage' => array_search($stage[1], $stageData),
                                    'time' => time()
                                ]),
                            };
                        }else{
                            $pid = $department_id;
                        }
                    }
                }

                $user = $UserModel->where('username', '=', $item['username'])->field('id,department_id')->find();
                if (!$user){
                    $uid = $UserModel->insertGetId([
                        'company_id' => $userData['company_id'],
                        'areas_id' => $userData['areas_id'],
                        'platform_id' => $userData['platform_id'],
                        'unit_id' => $userData['unit_id'],
                        'department_id' => $pid,
                        'role_id' => $roleInfo['id'],
                        'role_mode' => $roleInfo['mode'],
                        'type' => 4,
                        'username' => $item['username'],
                        'password' => encrypt_password(env('USER_PASSWORD')),
                        'sex' => $item['sex'],
                        'name' => $item['name'],
                        'avatar' => $item['sex'] == 1 ? $UserService->getDefaultAvatar('male') : $UserService->getDefaultAvatar('female'),
                        'province_id' => $userData['province_id'],
                        'city_id' => $userData['city_id'],
                        'area_id' => $userData['area_id'],
                        'province_name' => $userData['province_name'],
                        'city_name' => $userData['city_name'],
                        'area_name' => $userData['area_name'],
                        'time' => $time
                    ]);
                }else{
                    if ($user['department_id'] != $pid) throw new \Exception('账号【'.$item['username'].'】与部门【'.$item['department_name'].'】不匹配');
                    $uid = $user['id'];
                }
                $AddData[] = [
                    'unit_id' => $userData['unit_id'],
                    'operator_uid' => $userData['id'],
                    'uid' => $uid,
                    'level' => match ($item['level']) {
                        '轻度' => 1,
                        '中度' => 2,
                        '重度' => 3,
                        '密切' => 4
                    },
                    'reason' => $item['reason'],
                    'channel' => 8,
                    'time' => $time
                ];
            }
            if (!empty($AddData)) $FollowUserModel->insertAll($AddData);
            return true;
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            $this->line = $e->getLine();
            return false;
        }
    }

    /**
     * 干预人群导入
     * @param string $path 导入文件地址
     * @param array $userData 导入人信息
     * @return bool
     */
    public function InterfereUser(string $path, array $userData): bool
    {
        try {
            $ext = '.xlsx';
            $save_name = '/upload/'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            if (!file_put_contents('./public' . $save_name . $ext, file_get_contents($path))) throw new \Exception('文件加载失败！');
            $spreadSheet = IOFactory::load('./public' . $save_name . $ext);
            $sheetNames = $spreadSheet->getSheetNames();
            if ($sheetNames[0] != "干预人群") throw new \Exception('请上传正确的模板！');
            $sheet = $spreadSheet->getSheet(0);
            $limit = $sheet->getHighestDataRow('A');
            if ($limit < 4) throw new \Exception('请正确填写信息！');
            $Config = $this->getInterfereUserConfig();
            $UserModel = new UserModel();
            $InterfereUserModel = new InterfereUserModel();
            $CrisisTypeModel = new CrisisTypeModel();
            $CrisisLevelModel = new CrisisLevelModel();
            $DepartmentModel = new DepartmentModel();
            $RoleModel = new RoleModel();
            $UserService = new UserService($this->app);
            $LevelList = $CrisisLevelModel->where('unit_id','=',$userData['unit_id'])->field('id,name')->select();
            $LevelData = [];
            foreach ($LevelList as $value) {
                $LevelData[$value['name']] = $value['id'];
            }
            $TypeList = $CrisisTypeModel->where('unit_id','=',$userData['unit_id'])->field('id,name')->select();
            $TypeData = [];
            foreach ($TypeList as $value) {
                $TypeData[$value['name']] = $value['id'];
            }
            $SaveData = [];
            $time = time();
            $error = [];
            for ($i = 4; $i <= $limit; $i++) {
                $data = [];
                foreach ($Config as $value) {
                    $variate = $sheet->getCell($value['key'] . $i)->getValue();
                    if (empty($variate) && $value['required']) {
                        $error[] = '第'.$i.'行'.$value['key'] . $i.'列'.$value['name'] . '不能为空！';
//                        throw new \Exception($value['name'] . '不能为空！');
                    }
                    $data[$value['field']] = $variate;
                }
                $SaveData[] = $data;
            }
            if (!empty($error)) {
                throw new \Exception(implode("\n", $error));
            }
            $roleInfo = $RoleModel->where([
                ['unit_id','=',$userData['unit_id']],
                ['mode','=',3]
            ])->find();
            if (!$roleInfo) throw new \Exception('普通用户角色未创建！');
            $AddData = [];
            foreach ($SaveData as $item){
                $item['sex'] = $this->sexValue($item['sex']);
                $department_name = explode('_', $item['department_name']);
                $pid = 0;
                foreach ($department_name as $k => $v) {
                    $department_id = $DepartmentModel->where([
                        ['unit_id', '=', $userData['unit_id']],
                        ['name', '=', $v],
                    ])->value('id');
                    if (!$department_id) {
                        $pid = $DepartmentModel->insertGetId([
                            'unit_id' => $userData['unit_id'],
                            'pid' => $pid,
                            'level' => $k + 1,
                            'name' => $v,
                            'type' => 1,
                            'time' => $time
                        ]);
                    }else{
                        $pid = $department_id;
                    }
                }
                $user = $UserModel->where('username', '=', $item['username'])->field('id,department_id')->find();
                if (!$user){
                    $uid = $UserModel->insertGetId([
                        'company_id' => $userData['company_id'],
                        'areas_id' => $userData['areas_id'],
                        'platform_id' => $userData['platform_id'],
                        'unit_id' => $userData['unit_id'],
                        'department_id' => $pid,
                        'role_id' => $roleInfo['id'],
                        'role_mode' => $roleInfo['mode'],
                        'type' => 4,
                        'username' => $item['username'],
                        'password' => encrypt_password(env('USER_PASSWORD')),
                        'sex' => $item['sex'],
                        'name' => $item['name'],
                        'avatar' => $item['sex'] == 1 ? $UserService->getDefaultAvatar('male') : $UserService->getDefaultAvatar('female'),
                        'province_id' => $userData['province_id'],
                        'city_id' => $userData['city_id'],
                        'area_id' => $userData['area_id'],
                        'province_name' => $userData['province_name'],
                        'city_name' => $userData['city_name'],
                        'area_name' => $userData['area_name'],
                        'time' => $time
                    ]);
                }else{
                    if ($user['department_id'] != $pid) throw new \Exception('账号【'.$item['username'].'】与部门【'.$item['department_name'].'】不匹配');
                    $uid = $user['id'];
                }
                if (!isset($TypeData[$item['type_id']])) {
                    $type_id = $CrisisTypeModel->insertGetId([
                        'unit_id' => $userData['unit_id'],
                        'uid' => $userData['id'],
                        'name' => $item['type_id'],
                        'explain' => $item['type_id'],
                        'status' => 1,
                        'time' => $time
                    ]);
                }else{
                    $type_id = $TypeData[$item['type_id']];
                }
                if (!isset($LevelData[$item['level_id']])){
                    $level_id = $CrisisLevelModel->insertGetId([
                        'unit_id' => $userData['unit_id'],
                        'uid' => $userData['id'],
                        'name' => $item['level_id'],
                        'explain' => $item['level_id'],
                        'status' => 1,
                        'time' => $time
                    ]);
                }else{
                    $level_id = $LevelData[$item['level_id']];
                }
                $AddData[] = [
                    'unit_id' => $userData['unit_id'],
                    'operator_uid' => $userData['id'],
                    'uid' => $uid,
                    'channel' => 9,
                    'type_id' => $type_id,
                    'level_id' => $level_id,
                    'describe' => $item['describe'],
                    'priority' => match ($item['priority']){
                        '高度优先' => 1,
                        '中度优先' => 2,
                        '低度优先' => 3
                    },
                    'move_status' => 1,
                    'move_time' => $time,
                    'time' => $time
                ];
            }
            if (!empty($AddData)) $InterfereUserModel->insertAll($AddData);
            return true;
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            $this->line = $e->getLine();
            return false;
        }
    }


    /**
     * 干预人群导入-学院版
     * @param string $path 导入文件地址
     * @param array $userData 导入人信息
     * @return bool
     */
    public function SchoolInterfereUser(string $path, array $userData): bool
    {
        try {
            $ext = '.xlsx';
            $save_name = '/upload/'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            if (!file_put_contents('./public' . $save_name . $ext, file_get_contents($path))) throw new \Exception('文件加载失败！');
            $spreadSheet = IOFactory::load('./public' . $save_name . $ext);
            $sheetNames = $spreadSheet->getSheetNames();
            if ($sheetNames[0] != "学院制干预人群") throw new \Exception('请上传正确的模板！');
            $sheet = $spreadSheet->getSheet(0);
            $limit = $sheet->getHighestDataRow('A');
            if ($limit < 4) throw new \Exception('请正确填写信息！');
            $Config = $this->getSchoolInterfereUserConfig();
            $UserModel = new UserModel();
            $InterfereUserModel = new InterfereUserModel();
            $CrisisTypeModel = new CrisisTypeModel();
            $CrisisLevelModel = new CrisisLevelModel();
            $DepartmentModel = new DepartmentModel();
            $DepartmentLevelModel = new DepartmentLevelModel();
            $RoleModel = new RoleModel();
            $UserService = new UserService($this->app);
            $LevelList = $CrisisLevelModel->where('unit_id','=',$userData['unit_id'])->field('id,name')->select();
            $LevelData = [];
            foreach ($LevelList as $value) {
                $LevelData[$value['name']] = $value['id'];
            }
            $TypeList = $CrisisTypeModel->where('unit_id','=',$userData['unit_id'])->field('id,name')->select();
            $TypeData = [];
            foreach ($TypeList as $value) {
                $TypeData[$value['name']] = $value['id'];
            }
            $SaveData = [];
            $time = time();
            $error = [];
            for ($i = 4; $i <= $limit; $i++) {
                $data = [];
                foreach ($Config as $value) {
                    $variate = $sheet->getCell($value['key'] . $i)->getValue();
                    if (empty($variate) && $value['required']) {
                        $error[] = '第'.$i.'行'.$value['key'] . $i.'列'.$value['name'] . '不能为空！';
//                        throw new \Exception($value['name'] . '不能为空！');
                    }
                    $data[$value['field']] = $variate;
                }
                $SaveData[] = $data;
            }
            if (!empty($error)) {
                throw new \Exception(implode("\n", $error));
            }
            $roleInfo = $RoleModel->where([
                ['unit_id','=',$userData['unit_id']],
                ['mode','=',3]
            ])->find();
            if (!$roleInfo) throw new \Exception('普通用户角色未创建！');
            $AddData = [];
            foreach ($SaveData as $item){
                $item['sex'] = $this->sexValue($item['sex']);
                $is_department = 1;
                $department_name = explode('_', $item['department_name']);
                $pid = 0;
                foreach ($department_name as $v) {
                    $department_id = $DepartmentModel->where([
                        ['unit_id', '=', $userData['unit_id']],
                        ['pid', '=', $pid],
                        ['name', '=', $v],
                    ])->value('id');
                    if (!$department_id) {
                        $is_department = 0;
                    }
                    $pid = $department_id;
                }
                if ($is_department == 0) {
                    $pid = 0;
                    //创建部门
                    $stage = explode('_', $item['stage']);
                    if (count($stage) != 2) throw new \Exception($item['stage'] . '格式错误！');
                    $LevelInfo = $DepartmentLevelModel->where([
                        ['name', '=', $stage[0]],
                        ['unit_id', '=', $userData['unit_id']]
                    ])->find()->toArray();
                    if (!$LevelInfo) throw new \Exception($item['stage'] . '不存在！');
                    $stageData = json_decode($LevelInfo['level_rules'], true);
                    foreach ($department_name as $k => $v) {
                        $department_id = $DepartmentModel->where([
                            ['pid', '=', $pid],
                            ['name', '=', $v],
                            ['unit_id', '=', $userData['unit_id']]
                        ])->value('id');
                        if (!$department_id) {
                            $pid = match ($k) {
                                0 => $DepartmentModel->insertGetId([
                                    'unit_id' => $userData['unit_id'],
                                    'pid' => $pid,
                                    'level' => $k + 1,
                                    'name' => $v,
                                    'type' => 2,
                                    'mode' => $LevelInfo['id'],
                                    'time' => time()
                                ]),
                                default => $DepartmentModel->insertGetId([
                                    'unit_id' => $userData['unit_id'],
                                    'pid' => $pid,
                                    'level' => $k + 1,
                                    'name' => $v,
                                    'type' => 2,
                                    'mode' => $LevelInfo['id'],
                                    'stage' => array_search($stage[1], $stageData),
                                    'time' => time()
                                ]),
                            };
                        }else{
                            $pid = $department_id;
                        }
                    }
                }
                $user = $UserModel->where('username', '=', $item['username'])->field('id,department_id')->find();
                if (!$user){
                    $uid = $UserModel->insertGetId([
                        'company_id' => $userData['company_id'],
                        'areas_id' => $userData['areas_id'],
                        'platform_id' => $userData['platform_id'],
                        'unit_id' => $userData['unit_id'],
                        'department_id' => $pid,
                        'role_id' => $roleInfo['id'],
                        'role_mode' => $roleInfo['mode'],
                        'type' => 4,
                        'username' => $item['username'],
                        'password' => encrypt_password(env('USER_PASSWORD')),
                        'sex' => $item['sex'],
                        'name' => $item['name'],
                        'avatar' => $item['sex'] == 1 ? $UserService->getDefaultAvatar('male') : $UserService->getDefaultAvatar('female'),
                        'province_id' => $userData['province_id'],
                        'city_id' => $userData['city_id'],
                        'area_id' => $userData['area_id'],
                        'province_name' => $userData['province_name'],
                        'city_name' => $userData['city_name'],
                        'area_name' => $userData['area_name'],
                        'time' => $time
                    ]);
                }else{
                    if ($user['department_id'] != $pid) throw new \Exception('账号【'.$item['username'].'】与部门【'.$item['department_name'].'】不匹配');
                    $uid = $user['id'];
                }
                if (!isset($TypeData[$item['type_id']])) {
                    $type_id = $CrisisTypeModel->insertGetId([
                        'unit_id' => $userData['unit_id'],
                        'uid' => $userData['id'],
                        'name' => $item['type_id'],
                        'explain' => $item['type_id'],
                        'status' => 1,
                        'time' => $time
                    ]);
                }else{
                    $type_id = $TypeData[$item['type_id']];
                }
                if (!isset($LevelData[$item['level_id']])){
                    $level_id = $CrisisLevelModel->insertGetId([
                        'unit_id' => $userData['unit_id'],
                        'uid' => $userData['id'],
                        'name' => $item['level_id'],
                        'explain' => $item['level_id'],
                        'status' => 1,
                        'time' => $time
                    ]);
                }else{
                    $level_id = $LevelData[$item['level_id']];
                }
                $AddData[] = [
                    'unit_id' => $userData['unit_id'],
                    'operator_uid' => $userData['id'],
                    'uid' => $uid,
                    'channel' => 9,
                    'type_id' => $type_id,
                    'level_id' => $level_id,
                    'describe' => $item['describe'],
                    'priority' => match ($item['priority']){
                        '高度优先' => 1,
                        '中度优先' => 2,
                        '低度优先' => 3
                    },
                    'move_status' => 1,
                    'move_time' => $time,
                    'time' => $time
                ];
            }
            if (!empty($AddData)) $InterfereUserModel->insertAll($AddData);
            return true;
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            $this->line = $e->getLine();
            return false;
        }
    }



    /**
     * 干预人群导入（高校）
     * @param string $path 导入文件地址
     * @param array $userData 导入人信息
     * @return bool
     */
    public function InterfereUser2(string $path, array $userData): bool
    {
        try {
            $ext = '.xlsx';
            $save_name = './upload/'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname($save_name.$ext);
            folder_build($file_path);
            if (!file_put_contents($save_name . $ext, file_get_contents($path))) throw new \Exception('文件加载失败！');
            $spreadSheet = IOFactory::load($save_name . $ext);
            $sheetNames = $spreadSheet->getSheetNames();
            if ($sheetNames[0] != "干预人群") throw new \Exception('请上传正确的模板！');
            $sheet = $spreadSheet->getSheet(0);
            $limit = $sheet->getHighestDataRow('A');
            if ($limit < 4) throw new \Exception('请正确填写信息！');
            $Config = $this->getInterfereUserConfig();
            $UserModel = new UserModel();
            $InterfereUserModel = new InterfereUserModel();
            $CrisisTypeModel = new CrisisTypeModel();
            $CrisisLevelModel = new CrisisLevelModel();
            $DepartmentModel = new DepartmentModel();
            $RoleModel = new RoleModel();
            $UserService = new UserService($this->app);
            $LevelList = $CrisisLevelModel->where('unit_id','=',$userData['unit_id'])->field('id,name')->select();
            $LevelData = [];
            foreach ($LevelList as $value) {
                $LevelData[$value['name']] = $value['id'];
            }
            $TypeList = $CrisisTypeModel->where('unit_id','=',$userData['unit_id'])->field('id,name')->select();
            $TypeData = [];
            foreach ($TypeList as $value) {
                $TypeData[$value['name']] = $value['id'];
            }
            $SaveData = [];
            $time = time();
            $error = [];
            for ($i = 4; $i <= $limit; $i++) {
                $data = [];
                foreach ($Config as $value) {
                    $variate = $sheet->getCell($value['key'] . $i)->getValue();
                    if (empty($variate) && $value['required']) {
                        $error[] = '第'.$i.'行'.$value['key'] . $i.'列'.$value['name'] . '不能为空！';
//                        throw new \Exception($value['name'] . '不能为空！');
                    }
                    $data[$value['field']] = $variate;
                }
                $SaveData[] = $data;
            }
            if (!empty($error)) {
                throw new \Exception(implode("\n", $error));
            }
            $roleInfo = $RoleModel->where([
                ['unit_id','=',$userData['unit_id']],
                ['mode','=',3]
            ])->find();
            if (!$roleInfo) throw new \Exception('普通用户角色未创建！');
            $AddData = [];
            foreach ($SaveData as $item){
                $item['sex'] = $this->sexValue($item['sex']);
                $department_name = explode('_', $item['department_name']);
                $pid = 0;
                foreach ($department_name as $k => $v) {
                    $department_id = $DepartmentModel->where([
                        ['unit_id', '=', $userData['unit_id']],
                        ['name', '=', $v],
                    ])->value('id');
                    if (!$department_id) {
                        $pid = $DepartmentModel->insertGetId([
                            'unit_id' => $userData['unit_id'],
                            'pid' => $pid,
                            'level' => $k + 1,
                            'name' => $v,
                            'type' => 1,
                            'time' => $time
                        ]);
                    }else{
                        $pid = $department_id;
                    }
                }
                $user = $UserModel->where('username', '=', $item['username'])->field('id,department_id')->find();
                if (!$user){
                    $uid = $UserModel->insertGetId([
                        'company_id' => $userData['company_id'],
                        'areas_id' => $userData['areas_id'],
                        'platform_id' => $userData['platform_id'],
                        'unit_id' => $userData['unit_id'],
                        'department_id' => $pid,
                        'role_id' => $roleInfo['id'],
                        'role_mode' => $roleInfo['mode'],
                        'type' => 4,
                        'username' => $item['username'],
                        'password' => encrypt_password(env('USER_PASSWORD')),
                        'sex' => $item['sex'],
                        'name' => $item['name'],
                        'avatar' => $item['sex'] == 1 ? $UserService->getDefaultAvatar('male') : $UserService->getDefaultAvatar('female'),
                        'province_id' => $userData['province_id'],
                        'city_id' => $userData['city_id'],
                        'area_id' => $userData['area_id'],
                        'province_name' => $userData['province_name'],
                        'city_name' => $userData['city_name'],
                        'area_name' => $userData['area_name'],
                        'time' => $time
                    ]);
                }else{
                    if ($user['department_id'] != $pid) throw new \Exception('账号【'.$item['username'].'】与部门【'.$item['department_name'].'】不匹配');
                    $uid = $user['id'];
                }
                if (!isset($TypeData[$item['type_id']])) {
                    $type_id = $CrisisTypeModel->insertGetId([
                        'unit_id' => $userData['unit_id'],
                        'uid' => $userData['id'],
                        'name' => $item['type_id'],
                        'explain' => $item['type_id'],
                        'status' => 1,
                        'time' => $time
                    ]);
                }else{
                    $type_id = $TypeData[$item['type_id']];
                }
                if (!isset($LevelData[$item['level_id']])){
                    $level_id = $CrisisLevelModel->insertGetId([
                        'unit_id' => $userData['unit_id'],
                        'uid' => $userData['id'],
                        'name' => $item['level_id'],
                        'explain' => $item['level_id'],
                        'status' => 1,
                        'time' => $time
                    ]);
                }else{
                    $level_id = $LevelData[$item['level_id']];
                }
                $AddData[] = [
                    'unit_id' => $userData['unit_id'],
                    'operator_uid' => $userData['id'],
                    'uid' => $uid,
                    'channel' => 9,
                    'type_id' => $type_id,
                    'level_id' => $level_id,
                    'describe' => $item['describe'],
                    'priority' => match ($item['priority']){
                        '高度优先' => 1,
                        '中度优先' => 2,
                        '低度优先' => 3
                    },
                    'evaluate_status' => 2,
                    'evaluate_time' => $time,
                    'evaluate_uid' => $userData['id'],
                    'time' => $time
                ];
            }
            if (!empty($AddData)) $InterfereUserModel->insertAll($AddData);
            return true;
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            $this->line = $e->getLine();
            return false;
        }
    }


    /**
     * 干预人群导入-学院版（高校）
     * @param string $path 导入文件地址
     * @param array $userData 导入人信息
     * @return bool
     */
    public function SchoolInterfereUser2(string $path, array $userData): bool
    {
        try {
            $ext = '.xlsx';
            $save_name = './upload/'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname($save_name.$ext);
            folder_build($file_path);
            if (!file_put_contents($save_name . $ext, file_get_contents($path))) throw new \Exception('文件加载失败！');
            $spreadSheet = IOFactory::load($save_name . $ext);
            $sheetNames = $spreadSheet->getSheetNames();
            if ($sheetNames[0] != "学院制干预人群") throw new \Exception('请上传正确的模板！');
            $sheet = $spreadSheet->getSheet(0);
            $limit = $sheet->getHighestDataRow('A');
            if ($limit < 4) throw new \Exception('请正确填写信息！');
            $Config = $this->getSchoolInterfereUserConfig();
            $UserModel = new UserModel();
            $InterfereUserModel = new InterfereUserModel();
            $CrisisTypeModel = new CrisisTypeModel();
            $CrisisLevelModel = new CrisisLevelModel();
            $DepartmentModel = new DepartmentModel();
            $DepartmentLevelModel = new DepartmentLevelModel();
            $RoleModel = new RoleModel();
            $UserService = new UserService($this->app);
            $LevelList = $CrisisLevelModel->where('unit_id','=',$userData['unit_id'])->field('id,name')->select();
            $LevelData = [];
            foreach ($LevelList as $value) {
                $LevelData[$value['name']] = $value['id'];
            }
            $TypeList = $CrisisTypeModel->where('unit_id','=',$userData['unit_id'])->field('id,name')->select();
            $TypeData = [];
            foreach ($TypeList as $value) {
                $TypeData[$value['name']] = $value['id'];
            }
            $SaveData = [];
            $time = time();
            $error = [];
            for ($i = 4; $i <= $limit; $i++) {
                $data = [];
                foreach ($Config as $value) {
                    $variate = $sheet->getCell($value['key'] . $i)->getValue();
                    if (empty($variate) && $value['required']) {
                        $error[] = '第'.$i.'行'.$value['key'] . $i.'列'.$value['name'] . '不能为空！';
//                        throw new \Exception($value['name'] . '不能为空！');
                    }
                    $data[$value['field']] = $variate;
                }
                $SaveData[] = $data;
            }
            if (!empty($error)) {
                throw new \Exception(implode("\n", $error));
            }
            $roleInfo = $RoleModel->where([
                ['unit_id','=',$userData['unit_id']],
                ['mode','=',3]
            ])->find();
            if (!$roleInfo) throw new \Exception('普通用户角色未创建！');
            $AddData = [];
            foreach ($SaveData as $item){
                $item['sex'] = $this->sexValue($item['sex']);
                $is_department = 1;
                $department_name = explode('_', $item['department_name']);
                $pid = 0;
                foreach ($department_name as $v) {
                    $department_id = $DepartmentModel->where([
                        ['unit_id', '=', $userData['unit_id']],
                        ['pid', '=', $pid],
                        ['name', '=', $v],
                    ])->value('id');
                    if (!$department_id) {
                        $is_department = 0;
                    }
                    $pid = $department_id;
                }
                if ($is_department == 0) {
                    $pid = 0;
                    //创建部门
                    $stage = explode('_', $item['stage']);
                    if (count($stage) != 2) throw new \Exception($item['stage'] . '格式错误！');
                    $LevelInfo = $DepartmentLevelModel->where([
                        ['name', '=', $stage[0]],
                        ['unit_id', '=', $userData['unit_id']]
                    ])->find()->toArray();
                    if (!$LevelInfo) throw new \Exception($item['stage'] . '不存在！');
                    $stageData = json_decode($LevelInfo['level_rules'], true);
                    foreach ($department_name as $k => $v) {
                        $department_id = $DepartmentModel->where([
                            ['pid', '=', $pid],
                            ['name', '=', $v],
                            ['unit_id', '=', $userData['unit_id']]
                        ])->value('id');
                        if (!$department_id) {
                            $pid = match ($k) {
                                0 => $DepartmentModel->insertGetId([
                                    'unit_id' => $userData['unit_id'],
                                    'pid' => $pid,
                                    'level' => $k + 1,
                                    'name' => $v,
                                    'type' => 2,
                                    'mode' => $LevelInfo['id'],
                                    'time' => time()
                                ]),
                                default => $DepartmentModel->insertGetId([
                                    'unit_id' => $userData['unit_id'],
                                    'pid' => $pid,
                                    'level' => $k + 1,
                                    'name' => $v,
                                    'type' => 2,
                                    'mode' => $LevelInfo['id'],
                                    'stage' => array_search($stage[1], $stageData),
                                    'time' => time()
                                ]),
                            };
                        }else{
                            $pid = $department_id;
                        }
                    }
                }
                $user = $UserModel->where('username', '=', $item['username'])->field('id,department_id')->find();
                if (!$user){
                    $uid = $UserModel->insertGetId([
                        'company_id' => $userData['company_id'],
                        'areas_id' => $userData['areas_id'],
                        'platform_id' => $userData['platform_id'],
                        'unit_id' => $userData['unit_id'],
                        'department_id' => $pid,
                        'role_id' => $roleInfo['id'],
                        'role_mode' => $roleInfo['mode'],
                        'type' => 4,
                        'username' => $item['username'],
                        'password' => encrypt_password(env('USER_PASSWORD')),
                        'sex' => $item['sex'],
                        'name' => $item['name'],
                        'avatar' => $item['sex'] == 1 ? $UserService->getDefaultAvatar('male') : $UserService->getDefaultAvatar('female'),
                        'province_id' => $userData['province_id'],
                        'city_id' => $userData['city_id'],
                        'area_id' => $userData['area_id'],
                        'province_name' => $userData['province_name'],
                        'city_name' => $userData['city_name'],
                        'area_name' => $userData['area_name'],
                        'time' => $time
                    ]);
                }else{
                    if ($user['department_id'] != $pid) throw new \Exception('账号【'.$item['username'].'】与部门【'.$item['department_name'].'】不匹配');
                    $uid = $user['id'];
                }
                if (!isset($TypeData[$item['type_id']])) {
                    $type_id = $CrisisTypeModel->insertGetId([
                        'unit_id' => $userData['unit_id'],
                        'uid' => $userData['id'],
                        'name' => $item['type_id'],
                        'explain' => $item['type_id'],
                        'status' => 1,
                        'time' => $time
                    ]);
                }else{
                    $type_id = $TypeData[$item['type_id']];
                }
                if (!isset($LevelData[$item['level_id']])){
                    $level_id = $CrisisLevelModel->insertGetId([
                        'unit_id' => $userData['unit_id'],
                        'uid' => $userData['id'],
                        'name' => $item['level_id'],
                        'explain' => $item['level_id'],
                        'status' => 1,
                        'time' => $time
                    ]);
                }else{
                    $level_id = $LevelData[$item['level_id']];
                }
                $AddData[] = [
                    'unit_id' => $userData['unit_id'],
                    'operator_uid' => $userData['id'],
                    'uid' => $uid,
                    'channel' => 9,
                    'type_id' => $type_id,
                    'level_id' => $level_id,
                    'describe' => $item['describe'],
                    'priority' => match ($item['priority']){
                        '高度优先' => 1,
                        '中度优先' => 2,
                        '低度优先' => 3
                    },
                    'evaluate_status' => 2,
                    'evaluate_time' => $time,
                    'evaluate_uid' => $userData['id'],
                    'time' => $time
                ];
            }
            if (!empty($AddData)) $InterfereUserModel->insertAll($AddData);
            return true;
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            $this->line = $e->getLine();
            return false;
        }
    }
}